#!/bin/bash
# Vars:
# REPOS
# SKIP_PKG_ERASE

. $TONE_ROOT/lib/common.sh

mark_result()
{
	local ret=$?
	if [ $ret -eq 0 ]; then
		tpass "$*"
	else
		tfail "$*"
	fi
	echo
	return $ret
}

tpass()
{
	echo "[TestResult] $* PASSED"
}

tfail()
{
	echo "[TestResult] $* FAILED"
}

tskip()
{
	echo "[TestResult] $* SKIPPED"
}

debug_echo()
{
	[ x"$DEBUG" = "xy" ] && echo "[DEBUG] $*"
}

yum_test()
{
	logger "yum check"
	mark_result "yum_check"

	logger "yum -y update"
	mark_result "yum_update"
	if ! which python &> /dev/null; then
		ln -s /usr/bin/python3 /usr/bin/python
	fi
	logger "yum repoclosure"
	mark_result "yum_repoclosure"
}

rpm_test()
{
	if [ -f "/etc/anolis-release" ]; then
		if grep -q 7.* /etc/anolis-release; then
			[ -n "$REPOS" ] || REPOS="os updates extras"
		fi
		if grep -q 8.* /etc/anolis-release; then
			[ -n "$REPOS" ] || REPOS="BaseOS AppStream PowerTools"
		fi
	fi
	[ -n "$SKIP_PKG_ERASE" ] || SKIP_PKG_ERASE=n

	tmpdir=$(mktemp -d)
	pkglist="$tmpdir/pkglist.available"
	if yum help list | grep -q '\-\-available'; then
		yum list --available 2>/dev/null > $pkglist
	else
		yum list available 2>/dev/null > $pkglist
	fi
	debug_echo "$(wc -l $pkglist)"

	sed -i '1,2d' $pkglist
	while read line
	do
		pkg=$(echo $line | awk '{print $1}')
		repo=$(echo $line | awk '{print $3}')
		debug_echo "pkg: $pkg; repo: $repo"
		filter_repo $repo || continue
		pkg_install $pkg $repo
	done <$pkglist
}

filter_repo()
{
	[ -n "$REPOS" ] || return 0

	local repo=$1
	for r in $REPOS
	do
		debug_echo "$r =? $repo"
		[ x"$r" = x"$repo" ] && return 0
	done
	return 1
}

pkg_install()
{
	local pkg=$1
	local repo=$2
	local pkg_installed=0

	echo -e "\nPackage: $pkg; Repo: $repo"
	rpm -q $pkg &>/dev/null && pkg_installed=1
	logger "yum -y install $pkg" || {
		tfail "$repo: $pkg"
		return 1
	}

	if [ x"$SKIP_PKG_ERASE" != "xy" ] && [ "$pkg_installed" -ne 1 ]; then
		logger "yum -y erase $pkg" || {
			tfail "$repo: $pkg"
			return 1
		}
	fi
	tpass "$repo: $pkg"
	return 0
}

setup()
{
	logger "cat /etc/os-release"
	logger "uname -r"
	logger "yum repolist -v"
}

teardown()
{
	[ -d "$tmpdir" ] && rm -rf $tmpdir
}

run()
{
	echo -e "\nRun Anolis OS Package Smoke test: $tcase"
	$tcase
}

parse()
{
	awk -f $TONE_BM_SUITE_DIR/parse.awk
}
